package org.dromara.tearoom.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.tearoom.domain.TerCouponTemplate;
import org.dromara.tearoom.domain.bo.TerCouponTemplateBo;
import org.dromara.tearoom.domain.enums.CouponTakeTypeEnum;
import org.dromara.tearoom.domain.vo.TerCouponTemplateVo;
import org.dromara.tearoom.mapper.TerCouponTemplateMapper;
import org.dromara.tearoom.service.ITerCouponTemplateService;
import org.dromara.tearoom.util.WeekMaskUtils;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 优惠劵模板Service业务层处理
 *
 * @author ckj
 * @date 2025-04-21
 */
@RequiredArgsConstructor
@Service
public class TerCouponTemplateServiceImpl implements ITerCouponTemplateService {

    private final TerCouponTemplateMapper baseMapper;

    /**
     * 查询优惠劵模板
     *
     * @param id 主键
     * @return 优惠劵模板
     */
    @Override
    public TerCouponTemplateVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询优惠劵
     *
     * @param thirdPlateId 第三方平台ID
     * @return 优惠劵
     */
    @Override
    public TerCouponTemplateVo queryByThirdPlateId(String thirdPlateId) {
        TerCouponTemplateVo couponTemplateVo = baseMapper.selectVoOne(new LambdaQueryWrapper<TerCouponTemplate>().eq(TerCouponTemplate::getThirdPlateId,thirdPlateId));
        if(ObjectUtil.isEmpty(couponTemplateVo)){
            throw new ServiceException("平台编号为"+thirdPlateId+"的优惠券模版没有配置！");
        }
        return couponTemplateVo;
    }

    /**
     * 分页查询优惠劵模板列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 优惠劵模板分页列表
     */
    @Override
    public TableDataInfo<TerCouponTemplateVo> queryPageList(TerCouponTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TerCouponTemplate> lqw = buildQueryWrapper(bo);
        Page<TerCouponTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的优惠劵模板列表
     *
     * @param bo 查询条件
     * @return 优惠劵模板列表
     */
    @Override
    public List<TerCouponTemplateVo> queryList(TerCouponTemplateBo bo) {
        LambdaQueryWrapper<TerCouponTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TerCouponTemplate> buildQueryWrapper(TerCouponTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TerCouponTemplate> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TerCouponTemplate::getId);
        lqw.like(StringUtils.isNotBlank(bo.getName()), TerCouponTemplate::getName, bo.getName());
        lqw.eq(bo.getStatus() != null, TerCouponTemplate::getStatus, bo.getStatus());
        lqw.eq(bo.getThirdPlateId() != null, TerCouponTemplate::getThirdPlateId, bo.getThirdPlateId());
        lqw.eq(bo.getPlateType() != null, TerCouponTemplate::getPlateType, bo.getPlateType());
        lqw.eq(bo.getTakeType() != null, TerCouponTemplate::getTakeType, bo.getTakeType());
        lqw.eq(bo.getTotalCount() != null, TerCouponTemplate::getTotalCount, bo.getTotalCount());
        lqw.eq(bo.getTakeLimitCount() != null, TerCouponTemplate::getTakeLimitCount, bo.getTakeLimitCount());
        lqw.eq(bo.getTakeCount() != null, TerCouponTemplate::getTakeCount, bo.getTakeCount());
        lqw.eq(bo.getUseCount() != null, TerCouponTemplate::getUseCount, bo.getUseCount());
        lqw.eq(bo.getUsePrice() != null, TerCouponTemplate::getUsePrice, bo.getUsePrice());
        lqw.eq(bo.getProductScope() != null, TerCouponTemplate::getProductScope, bo.getProductScope());
        lqw.eq(bo.getValidityType() != null, TerCouponTemplate::getValidityType, bo.getValidityType());
        lqw.eq(bo.getValidStartTime() != null, TerCouponTemplate::getValidStartTime, bo.getValidStartTime());
        lqw.eq(bo.getValidEndTime() != null, TerCouponTemplate::getValidEndTime, bo.getValidEndTime());
        lqw.eq(bo.getFixedStartTerm() != null, TerCouponTemplate::getFixedStartTerm, bo.getFixedStartTerm());
        lqw.eq(bo.getFixedEndTerm() != null, TerCouponTemplate::getFixedEndTerm, bo.getFixedEndTerm());
        lqw.eq(bo.getType() != null, TerCouponTemplate::getType, bo.getType());
        lqw.eq(bo.getDiscountPercent() != null, TerCouponTemplate::getDiscountPercent, bo.getDiscountPercent());
        lqw.eq(bo.getDiscountPrice() != null, TerCouponTemplate::getDiscountPrice, bo.getDiscountPrice());
        lqw.eq(bo.getDiscountLimitPrice() != null, TerCouponTemplate::getDiscountLimitPrice, bo.getDiscountLimitPrice());
        if(ObjectUtil.isNotEmpty(params.get("createTimes"))){
            List<String> createTimes = StrUtil.splitTrim(params.get("createTimes").toString(), ',');
            String startTime = createTimes.get(0);
            String endTime = createTimes.get(1);
            lqw.between(TerCouponTemplate::getCreateTime,startTime,endTime);
        }
        return lqw;
    }

    /**
     * 新增优惠劵模板
     *
     * @param bo 优惠劵模板
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TerCouponTemplateBo bo) {
        processWeekMask(bo);
        TerCouponTemplate add = MapstructUtils.convert(bo, TerCouponTemplate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改优惠劵模板
     *
     * @param bo 优惠劵模板
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TerCouponTemplateBo bo) {
        TerCouponTemplate update = MapstructUtils.convert(bo, TerCouponTemplate.class);
        TerCouponTemplate entity=validateCouponTemplateExists(update.getId());
        // 校验发放数量不能过小（仅在 CouponTakeTypeEnum.USER 用户领取时）
        if (CouponTakeTypeEnum.isUser(entity.getTakeType())
                // 非不限制
                && ObjUtil.notEqual(entity.getTakeLimitCount(), TerCouponTemplate.TIME_LIMIT_COUNT_MAX)
                && bo.getTotalCount() < entity.getTakeCount()) {
            throw new ServiceException("发放数量不能小于已领取数量("+entity.getTakeCount()+")");
        }
        return baseMapper.updateById(update) > 0;
    }

    // 转换选择的星期为位掩码
    public void processWeekMask(TerCouponTemplateBo coupon) {
        if (coupon.getValidDaysMask() != null && !coupon.getValidDaysMask().isEmpty()) {
            int mask = 0;
            for (Integer day : coupon.getValidDaysMask()) {
                mask |= (1 << WeekMaskUtils.convertToBitPosition(day));
            }
            coupon.setValidDays(mask);
        }
    }



    private TerCouponTemplate validateCouponTemplateExists(Long id) {
        TerCouponTemplate couponTemplate = baseMapper.selectById(id);
        if (couponTemplate == null) {
            throw new ServiceException("优惠劵模板不存在");
        }
        return couponTemplate;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TerCouponTemplate entity){

    }

    /**
     * 校验并批量删除优惠劵模板信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 修改优惠卷状态
     *
     * @param id    用户ID
     * @param status 状态
     * @return 结果
     */
    @Override
    public int updateCouponStatus(Long id, Integer status) {
        TerCouponTemplateVo couponTemplateVo=baseMapper.selectVoById(id);
        if(ObjectUtil.isEmpty(couponTemplateVo)){
            throw new ServiceException("优惠卷不存在");
        }
        return baseMapper.update(null,
                new LambdaUpdateWrapper<TerCouponTemplate>()
                        .set(TerCouponTemplate::getStatus, status)
                        .eq(TerCouponTemplate::getId, id));
    }
}
